﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(ModelAnimationEvent))]
public class ModelAnimationEventEditr : Editor
{
    ModelAnimationEvent data;
    Dictionary<AnimationClipOverride, bool> pairs = new Dictionary<AnimationClipOverride, bool>();
    private void OnEnable()
    {
        data = target as ModelAnimationEvent;

        foreach (var clip in data.eventData.clips)
        {
            pairs.Add(clip, true);
        }
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (data.eventData == null)
            return;

        if(!Application.isPlaying)
        {
            var gameobjectPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(data.gameObject);
            var modelPath = AssetDatabase.GetAssetPath(data.eventData.animationModel);
            if (gameobjectPath != modelPath)
            {
                GUI.backgroundColor = Color.red;
            }
        }
        EditorGUILayout.ObjectField("model", data.eventData.animationModel, typeof(GameObject), false);
        GUI.backgroundColor = Color.white;

        foreach (var clip in data.eventData.clips)
        {
            EditorGUILayout.BeginVertical("helpBox");
            {
                EditorGUI.indentLevel = 1;
                pairs[clip] = EditorGUILayout.Foldout(pairs[clip], clip.kay.name, true);
                if (pairs[clip])
                {
                    var list= data.eventData.eventDatas.Where(x => x.clipName == clip.kay.name).ToList();
                    list.Sort((a, b) => a.time.CompareTo(b.time));
                    //list.Sort((a, b) => a.eventIndex.CompareTo(b.eventIndex));
                    foreach (var data in list)
                    {
                        EditorGUILayout.BeginVertical("Box");
                        {
                            EditorGUILayout.LabelField("function", data.functionName);
                            EditorGUILayout.LabelField("time", data.time.ToString());
                            for (int i = 0; i < data.parameters.Length; i++)
                            {
                                EditorGUILayout.LabelField(data.types[i], data.parameters[i]);
                            }
                        }
                        EditorGUILayout.EndVertical();
                    }
                }
            }
            EditorGUILayout.EndVertical();
        }

    }
}
